"use client"
import React, { useEffect, useState } from "react";
import {
    Button,
    Col,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,
    Switch,
    Table,
    TableProps,
    Tooltip,
    Tree
} from 'antd';

import { DatePicker } from 'antd';
import { CaretRightOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import EditorJobView from "./component/EditorJobView";
import { changeRoleStatus, delRole, listRole } from "@/clientApi/system/role";
import DataPermissionsView from "./component/DataPermissionsView";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { globalMessage } from "@/utils/message";
import RenderIconsCustom from "@/components/CustomIconSelector/conponents";
import { useConfirmModal } from "@/utils/ConfirmModal";
import { changeJobStatus, listJob, runJob } from "@/clientApi/monitor/job";
import { useRouter } from "next/navigation";

const JobView: React.FC = () => {
    const { confirm } = useConfirmModal();
    const navigateTo = useRouter();
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        jobName: undefined,
        jobGroup: undefined,
        status: undefined,

    };

    interface DataType {
    }

    const [form] = Form.useForm();
    const [record, setRecord] = useState<Record<string, any>>({});
    const [forceUpdateKey, setForceUpdateKey] = useState(0); // 用于强制更新组件的 key
    const [dataList, setDataList] = useState<DataType[]>([]);
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '任务编号',
            dataIndex: 'jobId',
            key: 'jobId',
            align: 'center'
        },
        {
            title: '任务名称',
            dataIndex: 'jobName',
            key: 'jobName',
            align: 'center'
        },
        {
            title: '任务组名',
            dataIndex: 'jobGroup',
            key: 'jobGroup',
            align: 'center'
        }, {
            title: '调用目标字符串',
            dataIndex: 'invokeTarget',
            key: 'invokeTarget',
            align: 'center'
        }, {
            title: 'cron执行表达式',
            dataIndex: 'cronExpression',
            key: 'cronExpression',
            align: 'center'
        }, {
            title: '下次执行时间',
            dataIndex: 'nextValidTime',
            key: 'nextValidTime',
            align: 'center'
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (_, record: any) => (
                <Switch key={forceUpdateKey + record.roleId} defaultValue={record.status === "0"}
                    onChange={(checked, event) => onChangeStatus(checked, event, record)} checkedChildren="开启"
                    unCheckedChildren="关闭" />
            )
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (_, record: any) => (
                <Space size="middle">
                    {record?.roleId !== 1 && (
                        <Tooltip title="修改">
                            <Button
                                type="link"
                                size="small"
                                icon={<RenderIconsCustom icon="edit" />}
                                onClick={() => EditClick(record)} />
                        </Tooltip>

                    )}
                    {record?.roleId !== 1 && (
                        <Tooltip title="删除">
                            <Button
                                type="link"
                                size="small"
                                icon={<DeleteOutlined />}
                                onClick={() => handleDelete(record)} />
                        </Tooltip>
                    )}
                    {record?.roleId !== 1 && (
                        <Tooltip title="执行一次">
                            <Button
                                type="link"
                                size="small"
                                icon={<CaretRightOutlined />}
                                onClick={() => handleRun(record)} />
                        </Tooltip>
                    )}
                    {record?.roleId !== 1 && (
                        <Tooltip title="数据权限">
                            <Button
                                type="link"
                                size="small"
                                icon={<RenderIconsCustom icon="password" />}
                                onClick={() => handleSchedulingLog(record)} />
                        </Tooltip>

                    )}

                </Space>
            ),
        },
    ];
    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [title, setTitle] = useState('');
    const [open, setOpen] = useState<boolean>(false);
    const [openDataPermissions, setOpenDataPermissions] = useState<boolean>(false);
    const [jobId, setJobId] = useState<string>();
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    function getList() {
        listJob(queryParams).then((res: any) => {
            setDataList(res.rows.map((item: any) => ({
                ...item,
                key: item.jobId // 使用 userId 作为唯一的 key
            })))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    const handleSearch = () => {
        form.validateFields().then(values => {
            console.log(values, 'values')
            setQueryParams(prevQueryParams => ({
                ...queryParams,
                jobName: values.jobName,
                status: values.status,
                jobGroup: values.jobGroup,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        form.resetFields();
        setQueryParams(initialQueryParams); // 重置为初始状态
    }

    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };
    // 修改按钮
    const EditClick = (e: any) => {
        setJobId(e.jobId)
        setTitle("修改用户")
        setOpen(true)
    }
    // 删除按钮
    const handleDelete = (e: any) => {
        const jobIds = e.jobId;
        confirm({
            title: '系统提示',
            content: (`是否确认删除用户编号为"${jobIds}"的数据项？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                delRole(jobIds).then((res: any) => {
                    if (res?.code === 200) {
                        globalMessage().info("删除成功")
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });

    }
    // 删除按钮
    const handleRun = (e: any) => {
        const jobIds = e.jobId;
        const jobGroup = e.jobGroup;
        confirm({
            title: '系统提示',
            content: (`确认要立即执行一次"${e.jobName}"任务吗？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                runJob(jobIds, jobGroup).then((res: any) => {
                    if (res?.code === 200) {
                        globalMessage().info("执行成功")
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });

    }

    // 调度日志
    const handleSchedulingLog = (e: any) => {
        navigateTo.push(`/monitor/job_log/${e.jobId}`)
        // setJobId(e.jobId)
        // setOpenDataPermissions(true)


    }


    const onChangeStatus = (checked: boolean, event: any, value: any) => {
        console.log(checked, event, value);
        const text = value.status === "0" ? "启用" : "停用";
        confirm({
            title: '系统提示',
            content: (`确认要"${text}"+"${value.jobName}"任务吗？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                changeJobStatus(value.jobId, checked === false ? "1" : "0").then((res: any) => {
                    if (res?.code === 200) {
                        globalMessage().info("修改成功").then(r => { })
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作
                setForceUpdateKey(prevKey => prevKey + 1); // 更新 key 以强制重新渲染组件
            },
        });
        // console.log(checked,event,value,value.status == "0")
    }


    return (
        <div className='home'>
            <Row gutter={20} style={{ paddingTop: "20px" }}>
                <Col span={24}>
                    <div><Form
                        form={form}
                        name="customized_form_controls"
                        style={{ marginTop: 10, marginLeft: 10, marginBottom: 10 }}
                        layout={useResponsiveLayout("inline")}>
                        <Form.Item
                            name="jobName"
                            label="任务名称">
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="jobGroup"
                            label="任务分组">
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="status"
                            label="状态">
                            <Select
                                style={{
                                    width: 120,
                                }}
                                allowClear
                                options={[
                                    {
                                        value: 0,
                                        label: '正常',
                                    }, {
                                        value: 1,
                                        label: '停用',
                                    },
                                ]}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                marginRight: 20,
                            }}>
                                查询
                            </Button>
                            <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form></div>
                    <div><Button type="primary" ghost onClick={() => {
                        setOpen(true);
                        setJobId(undefined);
                        setTitle("新增任务")
                    }} style={{ margin: 10 }}>
                        新增
                    </Button></div>
                    <Table<DataType> columns={columns} dataSource={dataList} pagination={{
                        current: queryParams.pageNum,
                        pageSize: queryParams.pageSize,
                        total: total,
                        showSizeChanger: true, // 显示分页尺寸切换器
                        pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                        onChange: handleTableChange
                    }} />
                </Col>
            </Row>
            {open && <EditorJobView title={title} open={open} jobId={jobId} OnCanCle={() => {
                setOpen(false);
                getList();
            }} />}


        </div>
    )
};
export default JobView;
